import os
import glob
import json
import requests
from docx import Document

# 彩云小译 API 配置信息
YOUR_TOKEN = '0ngrqcw8ye08k5pkqqz4'  # 替换为你的API Token
API_URL = "http://api.interpreter.caiyunai.com/v1/translator"

def translate(source, direction="auto2zh"):
    """
    调用彩云小译 API 进行翻译
    :param source: 要翻译的文本
    :param direction: 翻译方向，默认自动检测源语言并翻译成中文
    :return: 翻译后的文本
    """
    payload = {
        "source": source,
        "trans_type": direction,
        "request_id": "demo",
        "detect": True,
    }

    headers = {
        "content-type": "application/json",
        "x-authorization": f"token {YOUR_TOKEN}",
    }

    response = requests.post(API_URL, data=json.dumps(payload), headers=headers)

    if response.status_code == 200:
        return json.loads(response.text)["target"]
    else:
        print(f"Error: {response.status_code}, {response.text}")
        return None

def translate_docx(input_file, output_file):
    """
    翻译Word文档
    :param input_file: 输入的Word文档路径
    :param output_file: 输出的Word文档路径
    """
    # 读取原始Word文档
    doc = Document(input_file)

    # 创建一个新的Word文档
    new_doc = Document()

    for para in doc.paragraphs:
        if para.text.strip():  # 忽略空段落
            translated_text = translate(para.text.strip())
            if translated_text:
                new_doc.add_paragraph(translated_text)
            else:
                new_doc.add_paragraph(f"Error translating: {para.text.strip()}")
        else:
            new_doc.add_paragraph("")  # 保留空段落

    # 保存翻译后的Word文档
    new_doc.save(output_file)
    print(f"翻译完成，结果保存在：{output_file}")

if __name__ == "__main__":
    script_dir = os.path.dirname(os.path.abspath(__file__))  # 获取脚本所在目录
    docx_files = glob.glob(os.path.join(script_dir, "*.docx"))  # 查找所有.docx文件

    if not docx_files:
        print("未找到任何.docx文件")
    else:
        for docx_file in docx_files:
            output_filename = os.path.join(script_dir, "ch_" + os.path.basename(docx_file))  # 新文档名，前缀加"ch"
            translate_docx(docx_file, output_filename)